//
//  KSLoginViewController.swift
//  Merchant
//
//  Created by liuxm on 2017/8/11.
//  Copyright © 2017年 huanniu. All rights reserved.
//

import UIKit

/// 登录页面
class KSLoginViewController: KSBaseViewController, KSPageSwitchViewDelegate {
    
    /// 切换
    var pageSwitchView: KSPageSwitchView!
    // 倒计时
    var countdownTimer: Timer!
    // 倒计时时间
    var countdownSeconds = 60
    
    /// 账户登录
    @IBOutlet weak var accountLoginView: UIView!
    /// 验证码登录
    @IBOutlet weak var verificationCodeView: UIView!
    /// 切换
    @IBOutlet weak var switchView: UIView!
    /// 用户名/手机号
    @IBOutlet weak var accountTf: UITextField!
    /// 密码
    @IBOutlet weak var passwordTf: UITextField!
    /// 显示隐藏密码
    @IBOutlet weak var showPasswordBtn: UIButton!
    /// 手机号
    @IBOutlet weak var phoneNumTf: UITextField!
    /// 获取验证码按钮
    @IBOutlet weak var verificationBtn: UIButton!
    /// 验证码
    @IBOutlet weak var verificationCodeTf: UITextField!
    // 登录
    @IBOutlet var loginBtn: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        self.title = "登录"
        self.pageSwitchView = KSPageSwitchView(frame: self.switchView.frame)
        let array:Array<String> = ["账号登录", "验证码登录"]
        self.pageSwitchView.initView(item: array)
        self.pageSwitchView.delegate = self
        self.switchView.addSubview(self.pageSwitchView)
        
        self.loginBtn.setBackgroundImage(KSTools.createImageWithColor(color: KSColor.kColorMainRed), for: UIControlState.normal)
        self.loginBtn.setBackgroundImage(KSTools.createImageWithColor(color: KSColor.kColorButtonHighlight), for: UIControlState.highlighted)
        self.loginBtn.setBackgroundImage(KSTools.createImageWithColor(color: KSColor.kColorButtonDisabled), for: UIControlState.disabled)
        
        self.accountTf.text = KSUserDefaultsTools.getAccount()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        self.timerInvalidate()
    }
    
    // 登录
    @IBAction func loginBtnClick(_ sender: Any) {
        if accountLoginView.isHidden {
            if KSTools.checkPhoneNum(number: self.phoneNumTf.text!) {
                self.startLoading()
                request.requestLoginBysms(mobile: self.phoneNumTf.text!, code: self.verificationCodeTf.text!)
            } else {
                progressHUD.showMessage(text: "请输入正确的手机号", duration: 2, animated: true)
            }
        } else {
            self.startLoading()
            request.requestLogin(account: self.accountTf.text!, password: self.passwordTf.text!)
        }
    }
    
    // 显示密码
    @IBAction func showPassword(_ sender: Any) {
        self.showPasswordBtn.isSelected = !self.showPasswordBtn.isSelected
        if self.showPasswordBtn.isSelected {
            self.passwordTf.isSecureTextEntry = false
            self.showPasswordBtn.frame = CGRect(x: self.showPasswordBtn.frame.origin.x, y: self.showPasswordBtn.frame.origin.y, width: 22.5, height: 12.5)
        } else {
            self.passwordTf.isSecureTextEntry = true
            self.showPasswordBtn.frame = CGRect(x: self.showPasswordBtn.frame.origin.x, y: self.showPasswordBtn.frame.origin.y, width: 19.5, height: 12)
        }
    }
    
    // 注册
    @IBAction func registerBtnClick(_ sender: Any) {
        self.navigationController?.pushViewController(KSRegisterViewController(), animated: true)
    }
    
    // 忘记密码
    @IBAction func forgotPasswordBtnClick(_ sender: Any) {
        self.navigationController?.pushViewController(KSForgotPasswordViewController(), animated: true)
    }
    
    // 获取验证码
    @IBAction func getVerificationCodeBtnClick(_ sender: Any) {
        if KSTools.checkPhoneNum(number: self.phoneNumTf.text!) {
            self.startLoading()
            request.requestSendSMSLogin(mobile: self.phoneNumTf.text!, tempId: "3")
        } else {
            progressHUD.showMessage(text: "请输入正确的手机号", duration: 2, animated: true)
        }
    }
    
    // 账户编辑
    @IBAction func accountDidChanged(_ sender: Any) {
        if !accountLoginView.isHidden {
            if (self.accountTf.text?.isEmpty)! || (self.passwordTf.text?.isEmpty)! {
                self.loginBtn.isEnabled = false
            } else {
                self.loginBtn.isEnabled = true
            }
        }
    }
    
    // 密码
    @IBAction func passwordDidChange(_ sender: Any) {
        if !accountLoginView.isHidden {
            if (self.accountTf.text?.isEmpty)! || (self.passwordTf.text?.isEmpty)! {
                self.loginBtn.isEnabled = false
            } else {
                self.loginBtn.isEnabled = true
            }
        }
    }
    
    // 手机号
    @IBAction func phoneNumDidChange(_ sender: Any) {
        if !verificationCodeView.isHidden {
            if (self.phoneNumTf.text?.isEmpty)! || (self.verificationCodeTf.text?.isEmpty)! {
                self.loginBtn.isEnabled = false
            } else {
                self.loginBtn.isEnabled = true
            }
            
            if (self.phoneNumTf.text?.isEmpty)! {
                self.verificationBtn.isEnabled = false
            } else {
                self.verificationBtn.isEnabled = true
            }
        }
    }
    
    // 验证码
    @IBAction func verificationCodeDidChange(_ sender: Any) {
        if !verificationCodeView.isHidden {
            if (self.phoneNumTf.text?.isEmpty)! || (self.verificationCodeTf.text?.isEmpty)! {
                self.loginBtn.isEnabled = false
            } else {
                self.loginBtn.isEnabled = true
            }
        }
    }
    
    /// MARK: - KSRequestDelegate
    override func requestSuccess(result: String, apiType: KSApiType) {
        super.requestSuccess(result: result, apiType: apiType)
        // 账号登录
        if apiType == KSApiType.KSLogin {
            KSUserDefaultsTools.setAccount(self.accountTf.text!)
            let loginModel = KSLoginModel.deserialize(from: result)
            self.analyLoginByAccount(userInfo: (loginModel?.data)!)
            let appDelegate = UIApplication.shared.delegate as! AppDelegate
            appDelegate.switchHomePage()
        }
            // 快捷登录 - 手机号验证码
        else if apiType == KSApiType.KSLoginBySms {
            let loginModel = KSQuickLoginModel.deserialize(from: result)
            self.analyLoginBySms(userInfo: (loginModel?.data?.userInfo)!)
            let appDelegate = UIApplication.shared.delegate as! AppDelegate
            appDelegate.switchHomePage()
        }
            // 快捷登录 - 发送验证码
        else if apiType == KSApiType.KSSendCode {
            progressHUD.showMessage(text: "发送成功", duration: 2, animated: true)
            self.startcountdownTimer()
        }
    }
    
    // 开始倒计时
    private func startcountdownTimer() {
        self.timerInvalidate()
        
        self.verificationBtn.isEnabled = false
        self.verificationBtn.isUserInteractionEnabled = false
        self.verificationBtn.setTitle("60秒后重发", for: UIControlState.normal)
        self.countdownSeconds = 60
        self.countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(KSLoginViewController.timerRepeats), userInfo: nil, repeats: true)
    }
    
    @objc private func timerRepeats() {
        if self.countdownSeconds == 0 {
            self.verificationBtn.setTitle("获取验证码", for: UIControlState.normal)
            self.verificationBtn.isEnabled = true
            self.verificationBtn.isUserInteractionEnabled = true
            
            self.timerInvalidate()
        } else {
            self.countdownSeconds -= 1
            self.verificationBtn.setTitle("\(self.countdownSeconds)秒后重发", for: UIControlState.normal)
        }
    }
    
    private func timerInvalidate() {
        if self.countdownTimer != nil {
            self.countdownTimer.invalidate()
            self.countdownTimer = nil
        }
    }
    
    // MARK: - KSPageSwitchViewDelegate
    func pageSwitchClick(page: Int) {
        if page == 0 {
            accountLoginView.isHidden = false
            verificationCodeView.isHidden = true
            if (self.accountTf.text?.isEmpty)! || (self.passwordTf.text?.isEmpty)! {
                self.loginBtn.isEnabled = false
            } else {
                self.loginBtn.isEnabled = true
            }
        } else {
            accountLoginView.isHidden = true
            verificationCodeView.isHidden = false
            if (self.phoneNumTf.text?.isEmpty)! || (self.verificationCodeTf.text?.isEmpty)! {
                self.loginBtn.isEnabled = false
            } else {
                self.loginBtn.isEnabled = true
            }
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if accountLoginView.isHidden {
            self.phoneNumTf.resignFirstResponder()
            self.verificationCodeTf.resignFirstResponder()
        } else {
            self.accountTf.resignFirstResponder()
            self.passwordTf.resignFirstResponder()
        }
    }
    
    // 账户登录
    private func analyLoginByAccount(userInfo: KSUserInfoData) {
        KSUserDefaultsTools.setUserId((userInfo.user?.id)!)
        KSUserDefaultsTools.setUserToken((userInfo.access_token)!)
        KSUserDefaultsTools.setUserHaveLogined(true)
        KSUserDefaultsTools.setUserMobile((userInfo.user?.phone)!)
        KSUserDefaultsTools.setUserType((userInfo.user?.type)!)
    }
    
    // 快捷登录
    private func analyLoginBySms(userInfo: KSQuickLoginUserInfo) {
        KSUserDefaultsTools.setUserId(userInfo.user_id!)
        KSUserDefaultsTools.setUserToken(userInfo.access_token!)
        KSUserDefaultsTools.setUserHaveLogined(true)
        KSUserDefaultsTools.setUserMobile(userInfo.phone!)
        KSUserDefaultsTools.setUserType(userInfo.type!)
    }
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
